'''
Created on Sep 17, 2010

@author: diego
'''
import cv
from siftTracking import compare_desc


def compare_desc(desc1, newDescriptors):
    a = zip(desc1, newDescriptors)
    sum = 0
    for (x, y) in a:
        sum = sum + abs(x - y)
    return sum

def drawKeypoints(image, modelKeypoints):
    for ((x, y), laplacian, size, dir, hessian) in modelKeypoints:
        cv.Circle(image, (x, y), size, (200, 50, 50))


if __name__ == '__main__':
    capture = cv.CaptureFromCAM(1)
    storage = cv.CreateMemStorage(0)
    params = (0, 3000, 3, 1)
    
#    book1=cv.LoadImage("../resources/ontheroad.jpg",cv.CV_LOAD_IMAGE_GRAYSCALE)
    book1 = cv.LoadImage("../resources/cropontheroad.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)
    book2 = cv.LoadImage("../resources/ontheroad2.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)
#    match=cv.LoadImage("../resources/ontheroad.jpg")
    match = cv.LoadImage("../resources/cropontheroad.jpg")
    match2 = cv.LoadImage("../resources/ontheroad2.jpg")
    gray = cv.CreateImage((640, 480), 8, 1)
    frameSmooth = cv.CreateImage((640, 480), 8, 3)
    
    (modelKeypoints, modelDescriptors) = cv.ExtractSURF(book1, None, storage, params)
    print modelKeypoints[0]
    print modelKeypoints[0][1]
    drawKeypoints(match, modelKeypoints)

    while(True):
        frame = cv.QueryFrame(capture);
        cv.Smooth(frame, frameSmooth)
        cv.CvtColor(frameSmooth, gray, cv.CV_RGB2GRAY)
        (newKeypoints, newDescriptors) = cv.ExtractSURF(gray, None, storage, params)
        
        Nearest_Neighbor_Threshold = 1.0
        i = 0
        hits = 0
        for modelDesc in modelDescriptors:
            j = 0
            
            for newDesc in newDescriptors:
                
                if modelKeypoints[i][1] == newKeypoints[j][1] and compare_desc(modelDesc, newDesc) < Nearest_Neighbor_Threshold:
#                    hits=hits+1
                    drawKeypoints(frame, [newKeypoints[j]])
                j = j + 1
            i = i + 1        
        cv.ShowImage("match", match)
        cv.ShowImage("match2", frame)
        cv.WaitKey(30)
    
    
#    compare_desc(modelDescriptors, newDescriptors)
#        for ((x, y), laplacian, size, dir, hessian) in keypoints:
#            print "x=%modelDesc y=%modelDesc laplacian=%modelDesc size=%modelDesc dir=%f hessian=%f" % (x, y, laplacian, size, dir, hessian)
#    cv.Circle(frame, (x,y), size, (200,50,50))
    

